<template>
  <page-container title="重置密码">
    <el-form
      :model="form"
      label-width="120px"
      ref="resetFormRef"
      :rules="rules"
      class="reset-password-form"
    >
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input
          v-model="form.oldPassword"
          placeholder="请输入旧密码"
        ></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="form.newPassword"
          show-password
          placeholder="请输入新密码"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="form.confirmPassword"
          show-password
          placeholder="请再次输入新密码"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </page-container>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'

const resetFormRef = ref(null)
const form = reactive({
  oldPassword: '', // 示例旧密码，实际应用中应从后端获取
  newPassword: '',
  confirmPassword: ''
})

const rules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

function validateConfirmPassword(rule, value, callback) {
  if (value === '') {
    callback(new Error('请再次输入新密码'))
  } else if (value !== form.newPassword) {
    callback(new Error('两次输入的新密码不一致'))
  } else {
    callback()
  }
}

async function  submitForm() {
  resetFormRef.value.validate(async (valid) => {
    if (valid) {
      ElMessage.success('提交成功！')
      await userUpdatePasswordService({
        oldPassword: form.oldPassword,
        newPassword: form.newPassword
      })
    } else {
      ElMessage.error('验证失败')
    }
  })
}

function resetForm() {
  resetFormRef.value.resetFields()
}
</script>

<style scoped>
.page-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  background-color: #f0f0f0;
  padding: 20px;
  text-align: center;
}

.main {
  flex: 1;
  padding: 20px;
}

.reset-password-form {
  padding: 20px;
  width: 400px;
  margin-left: 0; /* 左边距为0 */
  margin-right: auto; /* 右边距自动调整 */
}

.el-input {
  width: 100%;
}
</style>
